﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using LiSAClient.Core;
using LiSAClient.Core.Interfaces;
using LiSAClient.Core.Messages;
using LiSAClient.Core.Models;
using LiSAClient.Core.Services;
using LiSAClient.Core.Services.Factories;
using LiSAClient.Core.Viewmodel;
using LiSAClient.LiSAService;

namespace LiSAClient.WpfClient.ViewModel.Projects.Edit
{
    class EditKeywordsViewModel : ContentViewModel, ICommitable
    {
        public ICommand Commit { get; private set; }

        public ICommand AddNewSearchKeyword { get; private set; }


        private Project project;
        public Project Project
        {
            get
            {
                return this.project;
            }

            set
            {
                this.Set(() => this.Project, ref this.project, value);
            }
        }

        private string newSearchKeyword;
        public string NewSearchKeyword
        {
            get
            {
                return this.newSearchKeyword;
            }

            set
            {
                this.Set(() => this.NewSearchKeyword, ref this.newSearchKeyword, value);
            }
        }

        #region Initializers
        public EditKeywordsViewModel(Project proj)
        {
            this.Project = proj;
            this.Commit = new RelayCommand(SaveProject);
            this.AddNewSearchKeyword = new RelayCommand(DoAddNewSearchKeyword);
        }
        #endregion

        #region methods

        /// <summary>
        /// Add the new searchkeyword to the list
        /// </summary>
        public void DoAddNewSearchKeyword()
        {
            if (string.IsNullOrWhiteSpace(this.NewSearchKeyword))
            {
                return;
            }
            var newKeaywords = new List<string>(this.Project.SearchKeywords) {this.NewSearchKeyword};
            this.Project.SearchKeywords = newKeaywords;
            this.NewSearchKeyword = string.Empty;
        }

        /// <summary>
        /// Save the project and close the window
        /// </summary>
        public void SaveProject()
        {
            MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Update Project?", "Update Confirmation", System.Windows.MessageBoxButton.YesNo);
            if (messageBoxResult == MessageBoxResult.Yes)
            {
                ServiceFactory.Instance.Get<ProjectService>().UpdateProject(this.Project);

                // Close the window
                if (this.Presenter != null)
                {
                    this.Presenter.SendClosingRequest();
                }
            }
        }
        #endregion
    }
}